// Ext.require('Ext.tab.*');

var SISTEMA = SISTEMA || {};
SISTEMA.tabs = [];

SISTEMA.TABS = {
    arr_tabs : [],
    addTab: function(t){
        this.arr_tabs.push(t);
    },
    removeTab:function(t){
	
    },
    isTab: function(tab_name){
        return _.find(this.arr_tabs, function(p){
            return p['nombre'] == tab_name;
        });  
    },
    getTab: function(tab_name){
        //if(!this.isTab(tab_name)) return false;
        return _.find(this.arr_tabs, function(p){
            return p['nombre'] == tab_name;
        });  
    },
    minimizarTodasLasVentanas: function(){
        //if(!this.isTab(tab_name)) return false;
        for (var i=0; i < this.arr_tabs.length; i++) {
            // console.info("minimizando ventanas del tab: ", this.arr_tabs[i].nombre)
            this.arr_tabs[i].minimizarVentanas();
        } 
		
    // console.log("tabs " + this.arr_tabs.length);
    }
};

/* -------------------------------------------------- */
function Tab(name){  
    this.nombre = name;  
    this.ventanas = [];  
    
    this.guardarEstadoVentanas = function(){
        //busco el Comp
        
        console.log("guardado");
        
        return true;
    //return this.edad;
    };

    this.tieneVentanas = function(){
        if(this.ventanas.length > 0) return true;
        return false;
    };

    this.addVentana= function(v){
        this.ventanas.push(v)       
    };

    this.minimizarVentanas = function(){
        for (i = 0; i < this.ventanas.length; i++) {
            // console.log("minimizando ventana: ", this.ventanas[i].nombre )
            var vent = Ext.getCmp(this.ventanas[i].nombre);
            
            if(vent && vent.isVisible()){
                if(!vent.collapsed){
                    vent.minimize();
                // console.info("ventana minimizada", this.ventanas[i].nombre )
                }
            }else{
            // console.error("no se encuentra la ventana", this.ventanas[i].nombre )
            }
            
        } 
    }    

    this.maximizarVentanas = function(){
        for (i = 0; i < this.ventanas.length; i++) {
            // console.log("maximizando ventana: ", this.ventanas[i].nombre )
            var vent = Ext.getCmp(this.ventanas[i].nombre);
            
            if(vent && vent.isVisible()){
                if(vent.collapsed){
                    vent.minimize();
                //                    console.info("ventana maximizando", this.ventanas[i].nombre )
                }
            }else{
            //                console.error("no se encuentra la ventana", this.ventanas[i].nombre )
            }
            
        } 
    }       
		
    this.restaurarVentanas = function(){
        for (i = 0; i < this.ventanas.length; i++) {
            //console.log("minimizando: " + this.ventanas[i].nombre);		   
            /*
		   Ext.getCmp(this.ventanas[i].nombre).maximize();
		   Ext.getCmp(this.ventanas[i].nombre).restore();
		   */
            //Ext.getCmp(this.ventanas[i].nombre).restaurar();
            } 
    }       
		
    this.cerrarVentanas = function(){
        for (i = 0; i < this.ventanas.length; i++) {
            //console.log("minimizando: " + this.ventanas[i].nombre);
            Ext.getCmp(this.ventanas[i].nombre).close();
        } 
    }       
	
}  
    
function Ventana(name){  
    this.nombre = name;  
    this.visible = false;
    this.minimizado = false;
    
    this.guardarEstado = function(){
        //busco el Comp
        
        //console.log("guardado");
        
        return true;
    //return this.edad;
    }   
}  

var t1 = new Tab("tab_main_documentos")
var t2 = new Tab("tab_main_transferencias")
var t3 = new Tab("tab_main_expedientes")

t1.addVentana(new Ventana("ventanaAltaDoc"));
t1.addVentana(new Ventana("ventanaDetalleFactura"));    

//t1.addVentana(new Ventana("ventanaDetalle"));
t2.addVentana(new Ventana("ventanaTransferir"));

t3.addVentana(new Ventana("ventanaExpediente"));    
//

// var t2 = new Tab("tab_2")
// t2.addVentana(new Ventana("ventana_3"))    
        
//SISTEMA.TABS.push(t1);  
SISTEMA.TABS.addTab(t1);  
SISTEMA.TABS.addTab(t2);  
SISTEMA.TABS.addTab(t3);  

// TABS.push(t2);      
    
// console.log(TABS);

//SISTEMA.TABS.getTab('tab_main_documentos').minimizarVentanas();


/* -------------------------------------------------- */

var seccionesFolder = "secciones/"; 

Ext.onReady(function(){


    var header = $.ajax({
        type: "POST",
        url: "ajax_parts/header.php",
        data: "accion=getDefinitivoUltimo",
        async: false
    }).responseText;

    var region_historia = $.ajax({
        type: "POST",
        url: "ajax_parts/region_historia.php",
        data: "",
        async: false
    }).responseText;
	
    var region_faxes = $.ajax({
        type: "POST",
        url: "ajax_parts/region_faxes.php",
        data: "",
        async: false
    }).responseText;

    //----- menu rck -------------------------------

    var store = Ext.create('Ext.data.TreeStore', {
        root: {
            expanded: true
        },
        proxy: {
            type: 'ajax',
            //            url: 'tree-data.json'
            url: 'ajax_php/getMenu.php'
        }
    });
    
    //console.log(store);
    
    var treePanel = Ext.create('Ext.tree.Panel', {
        id: 'tree-panel',
        // title: 'Sample Layouts',
        region:'north',
        split: true,
        //height: 450,
        height: screen.height * 0.5,
        //height: '30%',
        //minSize: 150,
        rootVisible: false,
        autoScroll: true,
        store: store
    });
    
    //console.log("screen.height", screen.height)
    
    //------------------------------------
    
    var faxesPanel = {
        id: 'faxes-panel',
        title: 'Info',
        region: 'center',
        //height: '40%',
        height: 80,
        //        bodyStyle: 'padding-bottom:15px;background:#eee;overflow:auto;',
        bodyStyle: 'padding-bottom:15px;background:#eee;'
        ,
        //        autoScroll: true,
        // html: 'sadas'
        //html: '<p class="details-info " onclick="abrirTab(\'main_fax\')"> - <a href="javascript:void(0)" >Hay <span class="cant_faxes">5<span> faxes.</a></p>'
        html: region_faxes
    };
    
	
    var detailsPanel = {
        id: 'details-panel',
        // title: 'Historial',
        title: 'Home',
        region: 'south',
        //height: '40%',
        height: 250,
        //        bodyStyle: 'padding-bottom:15px;background:#eee;overflow:auto;',
        bodyStyle: 'padding-bottom:15px;background:#eee;',
        //        autoScroll: true,
        //        html: '<p class="details-info">When you select a layout from the tree, additional details will display here.</p>'
        html: region_historia
    };
    
    
    // Assign the changeLayout function to be called on tree node click.
    treePanel.getSelectionModel().on('select', function(selModel, record) {
    
        // alert("me apreto " + record.getId());
        
        if (record.get('leaf')) {
        
            // Ext.getCmp('content-panel').layout.setActiveItem(record.getId() + '-panel');
            
            var tab_Id = 'tab_'+record.getId();
            //var tab_Id = 'tab_'+record.getId();
            //console.log(record);
            			
            if(tab_Id == "tab_acercade"){
                ventanaAcercaDe.show();
                return;
            }
			
            /*
            if(tab_Id == 'tab_main_documentos' || 
                tab_Id == 'tab_main_transferencias' ||
                    tab_Id == 'tab_main_movimientos' 
            )  Ext.getCmp('region_east').collapse();
            else Ext.getCmp('region_east').expand();
            */
			
            if(SISTEMA.tabs.is(tab_Id)){
                var tab = Ext.getCmp('panelPrincipal');
                tab.setActiveTab(tab_Id);                
                
                return false;
            } 
            
            SISTEMA.tabs.push(tab_Id); 
            
            //            console.log(SISTEMA.tabs);
            
            //            alert("asd");
            
            //            showStickySuccessToast("abriendo " + tab_Id + ".php" + "<br> ...");
            
            // Ext.getCmp('content-panel').layout.setActiveItem(record.getId() + '-panel');
            
            
            Ext.getCmp('panelPrincipal').add({
                id : tab_Id,
                title: record.data.text,
                iconCls: record.data.iconCls, //'menu_transferencias',
                bodyStyle: 'background-color: #FFF; padding:0; margin:0; overflow:auto',
                // html: 'Tab Body ' + pagName + '<br/><br/>', //+ Ext.example.bogusMarkup,
                autoLoad:{
                    "url": seccionesFolder + tab_Id + ".php",
                    "scripts":true
                }, //si anda!!
                closable: true,
                listeners : {
                    /*
                    'select': function() {
                        //stockInfo.load({params: {tCode:record.data.tCode}});
                        console.log("tab seleccionado malone");
                    },
                    */
                    'beforeclose' : function(){
                        
                        SISTEMA.tabs.remove(tab_Id);
                        
                        if(SISTEMA.TABS.isTab(tab_Id) && SISTEMA.TABS.getTab(tab_Id).tieneVentanas())
                            SISTEMA.TABS.getTab(tab_Id).cerrarVentanas();

                    //                        console.log(SISTEMA.tabs);
                    //                        console.log(this.getId());
                    //                        
                    // output : testPanel
                    //                        this.removeAll();
                    //                        alert(this.items.get(0).id); // output : undefined
                    }
                }
            }).show();

            
        /* 
            if (!detailEl) { //carga dinamicamente si no esta 
                var bd = Ext.getCmp('details-panel').body;
                bd.update('').setStyle('background','#fff');
                detailEl = bd.createChild(); //create default empty div
            }
            
            if(Ext.getDom(record.getId() + '-details'))
            {
                detailEl.hide().update(Ext.getDom(record.getId() + '-details').innerHTML).slideIn('l', {stopAnimation:true,duration: 200});
            }
            else
            {
                detailEl.hide().update("Sin Datos").slideIn('l', {stopAnimation:true,duration: 200});
            }
                 */
        }
        
        
    });
    

  
    Ext.create('Ext.container.Viewport', {
        renderTo: Ext.getBody(),
        layout: 'border',
        title: 'Ext Layout Browser',
        items: [{
            xtype: 'box',
            id: 'header',
            html: header, 
            //            html: '<h1> '+ SISTEMA.nombreAplicacion +'</h1> <a href="logout.php" style="float:right"><img src="images/logout.png" border="0" id="logout" class="switch" width="50" title="Salir"/></a><a href="#" ><img style="float:right" src="images/home.png" border="0" id="home" class="switch" width="50" title="Home" /></a>',
            region: 'north'
        //height: 30
        },/*{
				title: 'Movimientos',
				region: 'south',
				height: 150,
				minSize: 75,
				collapsible: true,
				split:true,
				expanded: true,
				maxSize: 250
				//cmargins: '5 0 0 0'
			}, {
            region: 'east',
            id: 'region_east',
            title: 'Movimientos',
            width: 180,
            collapsible: true,
            split:true,
            expanded: false
        //            weight: -110
        },*/{
            // layout: 'border',
            title: 'Menu',
            id: 'layout-browser',
            collapsible: true,
            region:'west',
            border: false,
            split:true,
            margins: '0 0 5 2',
            width: 180,
            //height: 500,
            minSize: 150,
            maxSize: 500,
            items: [treePanel, faxesPanel, detailsPanel]
        //items: [treePanel, faxesPanel, detailsPanel]
        // ,
        // could use a TreePanel or AccordionLayout for navigational items
        // }, {
        // region: 'south',
        // title: 'South Panel',
        // collapsible: true,
        // html: 'Information goes here',
        // split: true,
        // height: 100,
        // minHeight: 100
        // }, {
        // region: 'east',
        // title: 'East Panel',
        // collapsible: true,
        // split: true,
        // width: 150
        }, {
            region: 'center',
            id: 'panelPrincipal',
            autoScroll: true,
            // border: false,
            xtype: 'tabpanel', // TabPanel itself has no title
            activeTab: 0,      // First tab active by default
            // items   :   [tabPanel]          
            items:

			
			{
                id : 'tab_inicio',                
                iconCls: 'menu_home_2',
                //html: 'Bienvenidos a '+ SISTEMA.nombreAplicacion +' - User: ' + SISTEMA.UserLogin,
                bodyStyle: 'background-color: #FFF; padding:0; margin:0; overflow:auto',
				
                autoLoad:{
                    "url": seccionesFolder + "tab_inicio.php",
                    // "url": seccionesFolder + "tab_simple.php",
                    "scripts":true
                }, //si anda!!
				
				
                title: 'Inicio'
            },
			
            listeners :{
                'tabchange' : function(tabPanel, newTab) {                        
                    //console.log("Tab Activo: ", newTab);//si anda
                    //console.log("cambio de tab", tabPanel, newTab);//si anda
                    //tabPanel.guardarEstado();
                    //newTab.restaurarEstado();
                    //console.log("tabPanel: ", tabPanel, tabPanel.id)
						
                    // if(SISTEMA.TABS.getTab('tab_main_documentos') != newTab.id) 
                    //if(SISTEMA.tabs.is('tab_main_documentos')){//esta abierto						
                    //if(SISTEMA.TABS.isTab('tab_main_documentos') && SISTEMA.TABS.getTab('tab_main_documentos').tieneVentanas()){

					/*
				  
                    if(newTab.id == 'tab_main_transferencias'){                                                       
                        if(typeof oTableDocumentosTransferidos != 'undefined'){
                            refresh_data(oTableDocumentosPendientes);
                            refresh_data(oTableDocumentosTransferir);
                            refresh_data(oTableDocumentosTransferidos);
                        }						
                    }
					
                    if(newTab.id == 'tab_main_expedientes'){                                                       
                        if(typeof oTableExpedientesNew != 'undefined'){
                            refresh_data(oTableExpedientesNew);
                            refresh_data(oTableDocumentosNew);                            
                        }						
                    }
                                        
                    if(newTab.id == 'tab_main_tramites_archivados'){                                                       
                        if(typeof oTableTramitesArchivados != 'undefined'){
                            //refresh_data(oTableTramitesArchivados);                            
                        }						
                    }
                    
                    if(newTab.id == 'oTableTramitesCustodia'){                                                       
                        if(typeof oTableTramitesCustodia != 'undefined'){
                            //refresh_data(tab_main_tramites_custodia);                            
                        }						
                    }
                    
                    if(newTab.id == 'tab_main_documentos_master'){                                                       
                        if(typeof oTableDocumentosMaster != 'undefined'){
                            //refresh_data(oTableDocumentosMaster);                            
                        }						
                    }
                    
                    if(newTab.id == 'tab_main_fax'){                                                       
                        if(typeof oTableFax != 'undefined'){
                            //redibujarTablaFax();                            
                        }						
                    }
                    
                    if(newTab.id == 'tab_main_documentos_master_privado'){                                                       
                        if(typeof oTableDocumentosMaster_privado != 'undefined'){
                            //refresh_data(oTableDocumentosMaster_privado);                            
                        }						
                    }
                    
                    if(newTab.id == 'tab_main_documentos_server'){                                                       
                        if(typeof oTableDocumentosServer != 'undefined'){
                            refresh_data(oTableDocumentosServer);                            
                        }						
                    }
                    
                    if(newTab.id == 'tab_main_tramites_finalizados'){                                                       
                        if(typeof oTableTramitesFinalizados != 'undefined'){
                            //refresh_data(oTableTramitesFinalizados);                            
                        }						
                    } 
                    
                    if(newTab.id == 'tab_main_reportesareas_acept_server'){                                                       
                        if(typeof oTableDocumentosArea_acept != 'undefined'){
                            //refresh_data(oTableDocumentosArea_acept);                            
                        }						
                    } 
                    
                    if(newTab.id == 'tab_main_reportes_server'){                                                       
                        if(typeof oTableDocumentosReporte != 'undefined'){
                            //refresh_data(oTableDocumentosReporte);                            
                        }						
                    } 
                    
                    if(newTab.id == 'tab_main_reportesareas_server'){                                                       
                        if(typeof oTableDocumentosArea != 'undefined'){
                            //refresh_data(oTableDocumentosArea);                            
                        }						
                    } 
                    
                    if(newTab.id == 'tab_main_exptes_ant'){                                                       
                        if(typeof oTableExpedientesOld != 'undefined'){
                            //refresh_data(oTableExpedientesOld);                            
                        }						
                    } 

                    if(newTab.id == 'tab_usuarios_x_repart'){                                                       
                        if(typeof oTableUsuariosServer != 'undefined'){
                            // setTimeout(function(){
                            //oTableUsuariosServer.refresh(); 
                            // }, 1000); //ojo con chrome 500 , firefox con 100 anda!! 							                           
                        }						
                    }                                       	
				*/
				
                    SISTEMA.TABS.minimizarTodasLasVentanas();
                  
                    if(SISTEMA.TABS.isTab(newTab.id))
                        SISTEMA.TABS.getTab(newTab.id).maximizarVentanas();
						
                // var tab = SISTEMA.TABS.getTab(newTab.id);
                // if(tabPanel.id != 'tab_inicio' && tab.ventanas.length > 0) tab.minimizarVentanas();
											
                }                
            }
        }]
    });
            
			
    $("#loading").hide();   
    //Ext.get("loading").remove();

    $(".txt_bienvenido").dblclick(function(){
        // $(".datos_base").show()
        $(".datos_sector").toggle();					
    // $(".datos_base").toggle();					
    // $(".datos_base").css("")
    });
			
    $(".txt_bienvenido").click(function(){
        // $(".datos_base").show()
        $(".reloj").toggle();					
    // $(".datos_base").css("")
    });
    
    if(SISTEMA.oUser.arr_reparticiones.length > 1) $(".datos_sector").show();	

    $('.datos_sector').bind('contextmenu', function(e) {				
        //$('tr.filaPenadientes', oTableDocumentosPendientes.fnGetNodes()).bind('contextmenu', function(e) {  //anda?? NO		
        // $('.doc_trans').bind('contextmenu', function(e) {				
        e.preventDefault();				
        //alert("pepe 65124");
        //console.log(e)
				
        // var parts = $(this).attr("id").split("_");	
        //console.log("partes: ", parts)	
			
        // menuTransferencia_2.data.idDoc = parts[1];
        // menuTransferencia_2.data.docNumAnio = $(this).attr("title");
        // menuTransferencia_2.data.idTx = parts[3];
			
        //console.info(menuTransferencia_2.data)
			
        menuOpcionesUsuario.showAt(e.clientX, e.clientY);
    });	
		
    $("#boton_home").click(function(){					
        window.onbeforeunload = null; 
        location.reload(true) //vuelve a cargar los scripts		
        js_mysql_query("UPDATE admin_usuarios SET actualizo = 1 WHERE id_usuario = "+SISTEMA.UserId, {
            log:true
        });		
    });
			
});